import React, { Component } from 'react';

import { Get, Post } from '../utils/fetch';

/**
 * 针对特殊字典接口 /api/dict/xxxxx
 */
const dictDataHandler = (r) => {
    r.items = r.items || [];
    return r.items.map((item) => {
        return {value: item.id, name: item.value};
    });
};

class FormSelect extends Component {

    static defaultProps = {
        className: [],
        labelClassName: [],
        selectClassName: [],
        label: '',
        name: '',
        disabled: false,
        onChange: () => { },
        dataItem: {},
        dataList: [],
        isGet: true,
        dataUrl: null,
        dataHandler: (dataItem) => {
            return { value: dataItem.id, name: dataItem.name };
        }
    };

    state = {
        dataList: this.props.dataList,
        inputValue: this.props.dataItem[this.props.name]
    };

    componentDidMount = () => {
        if (this.props.dataUrl) {
            this.load(this.props.dataUrl);
        }
    };

    componentWillReceiveProps = (props) => {
        let { dataItem, name } = props;
        let { inputValue } = this.state;
        if (dataItem[name] && dataItem[name] !== inputValue) {
            inputValue = dataItem[name];
            this.setState({ inputValue });
        }
    };

    render() {
        return (
            <div className={['form-group'].concat(this.props.className).join(' ')}>
                <label className={["control-label"].concat(this.props.labelClassName).join(' ')} style={{ "marginTop": "5px", "marginRight": "5px" }}>{this.props.label}:</label>
                <select disabled={this.props.disabled} className={['form-control'].concat(this.props.selectClassName).join(' ')} name={this.props.name} value={this.state.inputValue} onChange={this._onChange}>
                    {this.state.dataList.map(this._renderItem)}
                </select>
                {this.props.children}
            </div>
        );
    }

    load = (dataUrl) => {
        (this.props.isGet ? Get : Post)(dataUrl)
            .then((r) => {
                let base = [{ name: '请选择', value: '' }];
                if (dataUrl.indexOf('/api/dict') !== -1) {
                    this.setState({dataList: base.concat(dictDataHandler(r))});
                } 
                else {
                    this.setState({ dataList: base.concat((r.content || r).map(this.props.dataHandler)) });
                }
            });
    };

    _renderItem = (item, index) => {
        return <option key={index} value={item.value}>{item.name}</option>;
    };

    _onChange = (evt) => {
        let { dataItem, name } = this.props;
        dataItem[name] = evt.target.value;
        if (global.isDebug) {
            console.log(`${dataItem} ${name} => ${dataItem[name]}`);
        }
        this.setState({ inputValue: dataItem[name] });

        console.log(dataItem);

        this.props.onChange(dataItem[name], name);
    };
}

export default FormSelect;